//
//  DDCreateAddressViewController.m
//  Dingdong
//
//  Created by 程强 on 16/11/11.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDCreateAddressViewController.h"
#import "KKTextView.h"
#import "KSPickerView.h"
#import "DDUserManager.h"
#import "DDAreaSet.h"

@interface DDCreateAddressViewController ()<UITextFieldDelegate,KSPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTxf;
@property (weak, nonatomic) IBOutlet UITextField *phoneTxf;
@property (weak, nonatomic) IBOutlet UITextField *countryTxf;
@property (weak, nonatomic) IBOutlet UITextField *areaTxf;
@property (weak, nonatomic) IBOutlet KKTextView *detailsTxt;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (strong, nonatomic) DDUserManager *manager;
@property (strong, nonatomic) DDAreaSet *areaSet;
@property (strong, nonatomic) DDAreaObj *selectCountry;
@property (strong, nonatomic) DDAreaObj *selectArea;
@property (strong, nonatomic) DDAreaObj *selectRegion;
@end

static NSString *areaStr = @"";


@implementation DDCreateAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DDUserManager new];
    [self layoutCreateAddressView];
    [self fetchArea];
}
- (void)layoutCreateAddressView
{
    if (self.vcType == DingDongAddressControllerTypeEdit) {
        self.nameTxf.text = self.addObj.name;
        self.phoneTxf.text = self.addObj.mobile;
        self.countryTxf.text = self.addObj.province;
        self.areaTxf.text = [NSString stringWithFormat:@"%@,%@",self.addObj.city,self.addObj.region];
        self.detailsTxt.text = self.addObj.addr;
    }
    self.detailsTxt.placeholder = @"The detail infomation...";
    self.saveBtn.layer.cornerRadius = 3.0;
}
#pragma mark --- 获取地区
- (void)fetchArea
{
    weak_Self(self);
    [[self.manager getArea:@"0"]subscribeNext:^(id x) {
        weakSelf.areaSet = x;
        if (weakSelf.vcType == DingDongAddressControllerTypeEdit) {
            [weakSelf getEditAreaInfo];
        }
    } error:^(NSError *error) {
        [weakSelf showMessageHUD:@"获取地址信息失败" delayHide:1.0];
    } completed:^{
        
    }];
}
- (void)getEditAreaInfo
{
    [self.areaSet.areaAry enumerateObjectsUsingBlock:^(DDAreaObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.region_id == self.addObj.province_id) {
            self.selectCountry = obj;
        }
    }];
    
    [self.selectCountry.children enumerateObjectsUsingBlock:^(DDAreaObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.region_id == self.addObj.city_id) {
            self.selectArea = obj;
        }
    }];
    
    [self.selectArea.children enumerateObjectsUsingBlock:^(DDAreaObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.region_id == self.addObj.region_id) {
            self.selectRegion = obj;
        }
    }];

}
- (IBAction)selectCountryClick:(id)sender
{
    [self resignKeyboard];
    KSPickerView *picker = [[KSPickerView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    picker.title = @"Select Country";
    picker.delegate  = self;
    picker.dataAry = self.areaSet.areaAry;
    picker.tag = 100;
    [self.view.window addSubview:picker];
}
- (IBAction)selectAreaClick:(id)sender
{
    [self resignKeyboard];
    if (!self.selectCountry) {
        [self showMessageHUD:@"Please select country" delayHide:1.0];
        return;
    }

    KSPickerView *picker = [[KSPickerView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    picker.title = @"Select area";
    picker.delegate  = self;
    picker.dataAry = self.selectCountry.children;
    picker.components = 2;
    picker.tag = 101;
    [self.view.window addSubview:picker];
    [self ksPickerView:picker didSelectRow:0 inComponent:0];
    areaStr = @"";
}
- (NSInteger)ksPickerView:(KSPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView.tag == 100) {
        return self.areaSet.areaAry.count;
    }else if (pickerView.tag == 101){
        if (component == 0) {
            return self.selectCountry.children.count;
        }else if (component == 1){
            return self.selectArea.children.count;
        }
    }
    return 0;
}
-(NSString*)ksPickerView:(KSPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView.tag == 100) {
        DDAreaObj *areaObj = self.areaSet.areaAry[row];
        return areaObj.local_name;
    }else if (pickerView.tag == 101){
        if (component == 0) {
            DDAreaObj *areaObj = self.selectCountry.children[row];
            return areaObj.local_name;
        }else if (component ==1){
            DDAreaObj *areaObj = self.selectArea.children[row];
            return areaObj.local_name;
        }
    }
    return @"";
}
- (void)ksPickerView:(KSPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView.tag == 101) {
        if (component == 0) {
            DDAreaObj *areaObj = self.selectCountry.children[row];
            self.selectArea = areaObj;
            [pickerView reloadData];
        }
    }
}
- (void)ksPickView:(KSPickerView *)pickerView didConfirmRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView.tag == 100) {
        DDAreaObj *country =self.areaSet.areaAry[row];
        if (self.selectCountry&&![country.region_id isEqualToNumber:self.selectCountry.region_id]) {
            self.areaTxf.text = @"";
            areaStr = @"";
        }
        self.selectCountry =country;
        self.countryTxf.text = self.selectCountry.local_name;
        
    }else{
        if (component == 0) {
            self.selectArea = self.selectCountry.children[row];
            NSString *area = self.selectArea.local_name;
            areaStr = [areaStr stringByAppendingString:area];
        }else if (component == 1){
            self.selectRegion = self.selectArea.children[row];
            NSString *area = self.selectRegion.local_name;
            areaStr = [areaStr stringByAppendingString:area];
        }
        self.areaTxf.text = areaStr;
    }
}
- (BOOL)checkInput
{
    if (self.nameTxf.text.length == 0) {
        [self showMessageHUD:@"Please input name" delayHide:1.0];
        return NO;
    }
    if (self.phoneTxf.text.length == 0) {
        [self showMessageHUD:@"Please input phone" delayHide:1.0];
        return NO;
    }
    if (!self.selectCountry) {
        [self showMessageHUD:@"Please select country" delayHide:1.0];
        return NO;
    }
    if (!self.selectArea) {
        [self showMessageHUD:@"Please select area" delayHide:1.0];
        return NO;
    }
    if (self.detailsTxt.text.length == 0) {
        [self showMessageHUD:@"Please input detail info" delayHide:1.0];
        return NO;
    }
    return YES;
}
- (IBAction)saveClick:(id)sender
{
    if (![self checkInput]) {
        return;
    }
    
    NSNumber *add_id = nil;
    if (self.vcType == DingDongAddressControllerTypeEdit) {
        add_id = self.addObj.addr_id;
    }
    
    weak_Self(self);
    [[self.manager addReceiveAddress:self.nameTxf.text phone:self.phoneTxf.text country:@"1" provinceId:self.selectCountry.region_id cityId:self.selectArea.region_id regionId:self.selectRegion.region_id region:self.selectRegion.local_name city:self.selectArea.local_name province:self.selectCountry.local_name addr:self.detailsTxt.text defAddr:@"1" add_id:add_id]subscribeNext:^(id x) {
        [weakSelf showMessageHUD:@"Save Success" delayHide:1.0];
        [weakSelf gotoBack];
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)resignKeyboard
{
    [self.nameTxf resignFirstResponder];
    [self.phoneTxf resignFirstResponder];
    [self.detailsTxt resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
